package com.cmcc.aregister.ui.activity;

import java.io.IOException;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.TextView;

import com.cmcc.aregister.R;
import com.cmcc.aregister.cs.constant.ConfigUtilHelper;
import com.oauth.utils.LoginEncryptUtils;

public class YdzqWebsiteLoading extends ParentActivity
{
    private final String TAG = "YdzqWebsiteLoading";
    private TextView backBtn, titleView;
    private WebView webview;
    private ProgressDialog progressDialog;
    Thread thread;
    private String phoneNum = "";
    private String callbackUrl = "";
    private boolean fromAdPage;

    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.ydzq_website_view);
        titleView = (TextView) findViewById(R.id.title);
        phoneNum = ConfigUtilHelper.getMobile(this);
        backBtn = (TextView) findViewById(R.id.back_btn);
        backBtn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v)
            {
                finish();
            }
        });
        fromAdPage = getIntent().getBooleanExtra("fromAdPage", false);
        webview = (WebView) findViewById(R.id.website_view);
        callbackUrl = getIntent().getStringExtra("callbackUrl");
        loadUrl();
    }

    private void loadUrl()
    {
        progressDialog = new ProgressDialog(this);
        progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        progressDialog.setTitle(getString(R.string.notice));
        progressDialog.setIcon(android.R.drawable.ic_dialog_info);
        progressDialog.setMessage(getString(R.string.loading_web));
        progressDialog.setIndeterminate(true);
        progressDialog.setCancelable(true);
        progressDialog.show();
        thread = new Thread(new Runnable() {
            @Override
            public void run()
            {
                WebSettings settings = webview.getSettings();
                settings.setAppCacheEnabled(true);
                settings.setCacheMode(WebSettings.LOAD_DEFAULT);
                settings.setAppCacheMaxSize(8 * 1024 * 1024);
                settings.setAllowFileAccess(true);
                webview.getSettings().setJavaScriptEnabled(true);
                webview.getSettings().setPluginsEnabled(true);
                webview.getSettings().setSupportZoom(true);
                try
                {
                    phoneNum = LoginEncryptUtils.encodeString(
                        "szicity20131119", phoneNum, true);

                }
                catch (IOException e)
                {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                MyWebViewClient myWebView = new MyWebViewClient();
                webview.setWebViewClient(myWebView);
                webview.addJavascriptInterface(new Click(), "android");
                StringBuffer url = new StringBuffer(
                    "http://wap.szicity.com/cm/yezhi/index.aspx?function=getLoginStatus&isLogin=true&phoneNum="
                        + phoneNum + "&ClientType=0&ClientChannel=2");
                if (callbackUrl != null && !callbackUrl.equals(""))
                {
                    url.append("&callbackUrl=");
                    url.append(callbackUrl);
                }
                webview.loadUrl(url.toString());

                webview.setWebChromeClient(new WebChromeClient() {
                    public void onProgressChanged(WebView view, int progress)
                    {
                        // 载入进度改变而触发
                        if (progress == 100)
                        {
                            mHandler.sendEmptyMessage(1);// 如果全部载入,隐藏进度对话框
                        }
                    }
                });
            }
        });
        thread.start();
    }

    class Click
    {
        public void alertUserLogin(String callbackUrl)
        {
            Intent intent = new Intent();
            intent.setClass(YdzqWebsiteLoading.this, UserLoginActivity.class);
            intent.putExtra("callbackUrl", callbackUrl);
            intent.putExtra("fromAdPage", fromAdPage);
            startActivity(intent);
        }
    }

    @Override
    // 设置回退
    public boolean onKeyDown(int keyCode, KeyEvent event)
    {
        if ((keyCode == KeyEvent.KEYCODE_BACK) && webview != null
            && webview.canGoBack())
        {
            webview.goBack();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    private class MyWebViewClient extends WebViewClient
    {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url)
        {
            mHandler.sendEmptyMessage(0);
            return super.shouldOverrideUrlLoading(view, url);
        }

        public void onPageStarted(WebView view, String url,
            android.graphics.Bitmap favicon)
        {
            mHandler.sendEmptyMessage(0);// 显示加载框
        }

        @Override
        public void onPageFinished(WebView view, String url)
        {
            // 加载完毕后，关闭图片阻塞
            webview.getSettings().setBlockNetworkImage(false);
            mHandler.sendEmptyMessage(1);// 如果全部载入,隐藏进度对话框
            if (progressDialog != null)
            {
                progressDialog.dismiss();
            }
        }

        @Override
        public void onReceivedError(WebView view, int errorCode,
            String description, String failingUrl)
        {
            // TODO Auto-generated method stub
            super.onReceivedError(view, errorCode, description, failingUrl);
            mHandler.sendEmptyMessage(1);// 如果全部载入,隐藏进度对话框
            if (progressDialog != null)
            {
                progressDialog.dismiss();
            }
        }
    }

    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg)
        {
            if (!Thread.currentThread().isInterrupted())
            {
                switch (msg.what)
                {
                case 0:// 显示进度对话框
                    if (progressDialog != null)
                    {
                        progressDialog.show();
                    }
                    break;
                case 1:// 隐藏进度对话框，不可使用dismiss()、cancel(),否则再次调用show()时，显示的对话框小圆圈不会动
                    if (progressDialog != null && progressDialog.isShowing())
                        progressDialog.hide();
                    break;
                }
            }
        }
    };

    @Override
    protected void onDestroy()
    {
        // TODO Auto-generated method stub
        super.onDestroy();
        if (ConfigUtilHelper.debug)
        {
            Log.i(TAG, "------onDestroy------");
        }
        if (progressDialog != null)
        {
            progressDialog.dismiss();
            progressDialog = null;
        }
    }

    @Override
    protected void onPause()
    {
        // TODO Auto-generated method stub
        super.onPause();
        if (ConfigUtilHelper.debug)
        {
            Log.i(TAG, "------onPause------");
        }
    }

    @Override
    protected void onRestart()
    {
        // TODO Auto-generated method stub
        super.onRestart();
        if (ConfigUtilHelper.debug)
        {
            Log.i(TAG, "------onRestart------");
        }
    }

    @Override
    protected void onResume()
    {
        // TODO Auto-generated method stub
        super.onResume();
        if (fromAdPage)
        {
            titleView.setText("开门红");
        }
        if (ConfigUtilHelper.debug)
        {
            Log.i(TAG, "------onResume------");
        }
    }

    @Override
    protected void onStart()
    {
        // TODO Auto-generated method stub
        super.onStart();
        if (ConfigUtilHelper.debug)
        {
            Log.i(TAG, "------onStart------");
        }
    }

    @Override
    protected void onStop()
    {
        // TODO Auto-generated method stub
        super.onStop();
        if (ConfigUtilHelper.debug)
        {
            Log.i(TAG, "------onStop------");
        }
    }

}
